package com.dchh.android.suverynew.act;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.dchh.android.suverynew.R;
import com.dchh.android.suverynew.adapter.TZPSListAdapter;
import com.dchh.android.suverynew.base.SBaseActivity;
import com.dchh.android.suverynew.common.SPreferencesManager;
import com.dhcc.android.base.base.MSApplication;
import com.dhcc.android.base.common.bean.Check;
import com.dhcc.android.base.common.bean.Node;
import com.dhcc.android.base.common.view.AlertDialog;
import com.dhcc.android.base.db.DBImportUtil;
import com.dhcc.android.base.db.DBManagerUtil;
import com.dhcc.android.base.utils.Constants;
import com.dhcc.android.base.utils.FileUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 村图纸拍摄
 *
 * @author zhoudan
 * @date 2016年2月22日
 */
public class CUNPhotoActivity extends SBaseActivity {

    private LinearLayout main;
    private ListView listview;
    private List<Map<String, String>> dataList = new ArrayList<Map<String, String>>();
    private TZPSListAdapter adapter;

    private SharedPreferences sp;
    private String root;
    private String taskName;
    private String dbPath;

    private DBManagerUtil dbManagerUtil;
    private String beizhu2 = "2图纸";
    private String dcqb;
    private String cunmc;

    private String period;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.paper_photo_add_list);
    }

    @Override
    protected void setTitle(TextView toolbar_title) {
        toolbar_title.setText("村列表");
    }

    @Override
    public void initView() {
        root = SPreferencesManager.getValue(MSApplication.TASK_SAVE_PATH,
                FileUtil.getSavePath());
        taskName = getIntent().getStringExtra("taskName");
        dbPath = root + "/" + taskName + "/TASK/TRANSPORT/DATA.db";

        period = getIntent().getStringExtra("period");
        period = period.contains("早稻面积") ? "春播面积" : period;
        dcqb = period + "-" + "遥感面积调查表";

        dbManagerUtil = DBManagerUtil.getInstance(dbPath, this);
        getDatas();
        listview = (ListView) main.findViewById(R.id.photo_listView);
        if (adapter == null) {
            adapter = new TZPSListAdapter(this, dataList, node, 2);
            adapter.setOnOperateListener(listener);
            listview.setAdapter(adapter);
        }
        listview.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
                Constants.tzps_parent = dataList.get(position);
                Constants.tzps_node = node;
                Intent intent = new Intent(CUNPhotoActivity.this, YFPhotoActivity.class);
                intent.putExtra("period", period);
                intent.putExtra("taskName", taskName);
                startActivity(intent);
                overridePendingTransition(R.anim.push_right_in, R.anim.push_left_out);
            }
        });
    }

    TZPSListAdapter.OnOperateListener listener = new TZPSListAdapter.OnOperateListener() {

        @Override
        public void OnTake(int position) {
            String yfc = dataList.get(position).get("yfcount");
            String imgc = dataList.get(position).get("imgcount");

            int yf = 0, img = 0;
            if (yfc != null) {
                yf = Integer.valueOf(yfc);
            }
            if (imgc != null) {
                img = Integer.valueOf(imgc);
            }

            //判断下级的图纸是否拍摄完成
            //浙江不拍摄样方图纸
            if (ifYfbh(position) == false) {
                isAlertDialog(CUNPhotoActivity.this, "下级样方的图纸拍摄未完成，请先完成样方图纸拍摄！", null, "确定");
            } else {
                Constants.tzps_parent = dataList.get(position);
                Constants.tzps_node = node;

                Intent intent = new Intent(CUNPhotoActivity.this, TZPhotoActivity.class);
                intent.putExtra("type", 2);
                intent.putExtra("period", period);
                intent.putExtra("taskName", taskName);
                startActivity(intent);
            }
        }

        private boolean ifYfbh(int position) {
            String cun = dataList.get(position).get("CUNMC");
            // TODO Auto-generated method stub
            List<String> list0 = new ArrayList<String>();
            List<String> list3 = new ArrayList<String>();
            String YFBH0 = "";
            String YFBH3 = "";
            SQLiteDatabase database = SQLiteDatabase.openOrCreateDatabase(dbPath, null);
            String selectSQL0 = "select * from PHOTO where 村级行政区名称='" + String.valueOf(cun) + "' and TYPE='0'";
            String selectSQL3 = "select * from PHOTO where 村级行政区名称='" + String.valueOf(cun) + "' and TYPE='3'";
            Cursor cursor0 = database.rawQuery(selectSQL0, null);
            while (cursor0.moveToNext()) {
                YFBH0 = cursor0.getString(cursor0.getColumnIndex("样方编号"));
                list0.add(YFBH0);
            }
            cursor0.close();

            Cursor cursor3 = database.rawQuery(selectSQL3, null);
            while (cursor3.moveToNext()) {
                YFBH3 = cursor3.getString(cursor3.getColumnIndex("样方编号"));
                list3.add(YFBH3);
            }
            cursor0.close();
            cursor3.close();
            database.close();
            Log.i("GTY", list0.toString() + ">>>>>>>>>>>>>>>" + list3.toString());

            boolean flag = false;
            for (int i = 0; i < list0.size(); i++) {
                flag = false;
                for (int n = 0; n < list3.size(); n++) {
                    if (list0.get(i).equalsIgnoreCase(list3.get(n))) {
                        flag = true;
                        break;
                    } else {
                        flag = false;
                    }
                }
            }

            return flag;
        }

        @Override
        public void OnShow(int position) {
            Constants.tzps_parent = dataList.get(position);
            Constants.tzps_node = node;

            Intent intent = new Intent(CUNPhotoActivity.this, TZPhotoActivity.class);
            intent.putExtra("type", 2);
            intent.putExtra("period", period);
            intent.putExtra("taskName", taskName);
            startActivity(intent);
            overridePendingTransition(R.anim.push_right_in, R.anim.push_left_out);
        }
    };


    private void isAlertDialog(final Activity activity, String str, String right, String left) {
        final AlertDialog alertDialog = new AlertDialog(activity, str, null, left);
        alertDialog.show();
        alertDialog.setClicklistener(new AlertDialog.ClickListenerInterface() {

            @Override
            public void doConfirm() {
                alertDialog.dismiss();
            }

            @Override
            public void doCancel() {
                alertDialog.dismiss();
            }
        });
    }


    //    private Map<String, String> parent = null;
    private Node node;

    private void getDatas() {
        // 取到配置文件中当前层级的节点
        node = Constants.nodelist.get(0);
        Check check = node.getCheck();


        // 获取数据库中当前层级的下级数据列表
        String[] fields = {node.getFeild(), node.getItem().getFeild(), "rowid"};
        try {
            DBImportUtil.openDatabase(root, Constants.currentTask.getTitle(), "/TASK/DATA.db");
            if (check == null) {
                dataList = DBImportUtil.listData(node.getTable(), fields, null, null);
            } else {
                String fld = check.getPfeild().toUpperCase();
                String value = Constants.tzps_parent.get(fld);
                dataList = DBImportUtil.listData(node.getTable(), fields, check.getFeild(), value);
            }
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(this, "操作外部数据库出错", Toast.LENGTH_SHORT).show();
        }


        dodata();

    }

    private void dodata() {
        Node nd = Constants.nodelist.get(1);
        Check ck = nd.getCheck();
        String yfdbpath = root + "/" + taskName + "/TASK/DATA.db";
        String yftable = nd.getTable();
        String key = ck.getFeild();
        String fld = ck.getPfeild().toUpperCase();

        //处理数据
        for (Map<String, String> map : dataList) {
            cunmc = map.get("CUNMC");
            String where = " 村级行政区名称 = '" + cunmc + "' and DCQB = '" + dcqb + "' and TYPE = '2'";
            int c = dbManagerUtil.getTZPhotoCount("PHOTO", where, dbPath);
            map.put("flag", String.valueOf(c));
            System.out.println("村：" + c);

            //样方
            String value = map.get(fld);
            String w1 = key + " = '" + value + "'";
            int c1 = dbManagerUtil.getTZPhotoCount(yftable, w1, yfdbpath);
            map.put("yfcount", String.valueOf(c1));

            //照片
            String w2 = " 村级行政区名称 = '" + cunmc + "' and DCQB = '" + dcqb + "' and TYPE = '3'";
            int c2 = dbManagerUtil.getTZPhotoCount("PHOTO", w2, dbPath);
            map.put("imgcount", String.valueOf(c2));
        }
    }

    @Override
    protected void onResume() {
        super.onResume();

        if (Constants.data_refresh) {
            dodata();
            adapter.notifyDataSetChanged();
        }

    }

}
